<template>
  <div class="spell-listen-test">
    <Header :isGoBack="false">
      <!-- <template v-slot:left>
        <div>
          {{ checkedBookData.edition_name }}- {{ checkedBookData.grade_name }}>
          {{ $store.getters.categoryList[category].title }}(普通模式)
        </div>
      </template> -->
      <template v-slot:right>
        <div class="test-btn">
          <el-dropdown style="margin-right: 20px;" trigger="click" @command="handleCommand">
            <span class="el-dropdown-link">
              换单词<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in listenWordList" :key="item.id" :disabled="item.id == spellId"
                :command="item">{{ item.content
                }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span v-if="!isSubmit">计时：{{ testTime | filterTime }}</span>
          <span v-if="!isSubmit" class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="submitPaper">交卷</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="$goRouter('naturalSpellCenter', $route.query)">
              返回学习中心
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <div class="listen-test-container w1200">
      <h4 class="listen-test-title">{{ title + "-" + content }}</h4>
      <div class="listen-test-paper">
        <ul class="listen-test-list">
          <li class="listen-test-list-item" v-for="(wordData, index) in wordList" :key="wordData.id">
            <ListenTestItem :wordData="wordData" :spellId="spellId" :isSubmit="isSubmit" @postSpellVoice="(data, blob) => {
                postSpellVoice(data, blob, index);
              }
              " @pauseRecord="pauseRecord" ref="listen-test-item"></ListenTestItem>
          </li>
        </ul>
        <div class="paper-btn" v-if="isSubmit">
          <el-button class="button button-bg-primary" @click="$goRouter('spellTestAfterStudy', $route.query)"
            v-if="avgScore >= 80">
            去闯关
          </el-button>
          <span v-else>
            <el-button class="button button-bg-primary" @click="$goRouter('spellStudy', $route.query)" >
              重新学习
            </el-button>
            <el-button class="button button-bg-primary" @click="goNextGroup">
              下一组
            </el-button>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ListenTestItem from "./ListenTestItem.vue";
import { getNaturalSpellWord, postStudyStep } from "@/api/naturalSpell";
import { postSpellVoice } from "@/api/naturalSpell";
export default {
  data() {
    return {
      listenWordList: [],
      timer: null,
      testTime: 0,
      title: "",
      content: '',
      spellId: "",
      wordList: [],
      isSubmit: false,
      avgScore: 0,
      isOpenMessageBox: false,
      isSubmitVoice: false,
    };
  },
  watch: {
    "$route.query.checkedTypeId"(newVal, oldVal) {
      this.spellId = newVal
      this.title = this.$route.query.checkedTitle;
      this.getNaturalSpellWord();
      // this.spellStudyBoxKey += 1
    },
    immediate: true
  },
  methods: {
    goNextGroup(){
      let index= this.listenWordList.findIndex(item=>item.id==this.spellId)
      if(index>=this.listenWordList.length-1){
        this.$confirm('该模块已经学习完毕,是否返回学习中心?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          this.$goRouter('naturalSpellCenter', this.$route.query)
        }).catch(() => {
          console.log('停留当前模块');         
        });
        return
      }
      this.content = this.listenWordList[index+1].content
      this.testTime=0
      this.isSubmit=false
      let { checkedTitle } = this.$route.query
      let {source}=this.listenWordList[index+1]
      localStorage.setItem(
        "spellCheckedData",
        JSON.stringify(this.listenWordList[index+1])
      );
      this.$goRouter("spellListenTest", {
        checkedTypeId: this.listenWordList[index+1].id,
        checkedTitle,
        source
      });
    },
    handleCommand(item) {
      this.content = item.content
      let { checkedTitle, source } = this.$route.query
      localStorage.setItem(
        "spellCheckedData",
        JSON.stringify(item)
      );
      this.testTime=0
      this.isSubmit=false
      this.$goRouter("spellListenTest", {
        checkedTypeId: item.id,
        checkedTitle,
        source
      });
    },
    submitPaper() {
      this.pauseRecord();
      let number = 0;
      this.wordList.forEach((item) => {
        if (!item.isAnswer) {
          number++;
        }
      });
      if (!this.isOpenMessageBox) {
        this.isOpenMessageBox = true;
        this.$confirm(
          `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否确认提交？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            beforeClose: (action, instance, done) => {
              this.isOpenMessageBox = false;
              done();
            },
          }
        )
          .then(() => {
            this.postPaper();
          })
          .catch(() => {
            return false;
          });
      }
    },
    pauseRecord() {
      this.$refs["listen-test-item"].forEach((item) => {
        item.pauseRecord();
      });
    },
    postPaper() {
      this.isSubmit = true;
      clearInterval(this.timer);
      let sumScore = 0;
      this.wordList.forEach((item) => {
        if (item.isAnswer) {
          sumScore += item.score;
        }
      });
      this.avgScore = sumScore / this.wordList.length;
      if (this.avgScore >= 80) {
        this.postStudyStep();
      }
    },
    postStudyStep() {
      if (Number(this.$route.query.source) >= 3) {
        return;
      }
      let params = {
        elementId: this.spellId,
        source: 3,
      };
      postStudyStep(params).then((res) => {
        console.log(res);
      });
    },
    postSpellVoice(data, blob, index) {
      this.isSubmitVoice = true;
      postSpellVoice(data)
        .then((res) => {
          this.isSubmitVoice = false;
          if (res.code == 200) {
            this.$emit("recordedData", res.data);
            this.recordedData(res.data, blob, index);
          }
        })
        .catch(() => {
          this.isSubmitVoice = false;
        });
    },
    recordedData(data, blob, index) {
      let wordData = this.wordList[index];
      this.$set(wordData, "score", data.score);
      this.$set(wordData, "result", data.context.lines[0].words[0]);
      this.$set(wordData, "isAnswer", true);
      this.$set(wordData, "fileData", window.URL.createObjectURL(blob));
    },
    goStudyCenter() {
      this.$confirm(`试卷还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.$goRouter("naturalSpellCenter", this.$route.query);
        })
        .catch(() => {
          return false;
        });
    },
    getNaturalSpellWord() {
      let params = {
        id: this.spellId,
      };
      getNaturalSpellWord(params).then((res) => {
        if (res.code == 200) {
          this.wordList = res.data;
          this.setTimer();
        }
        if (res.code == 405) {
          this.$confirm(`暂无试题`, "提示", {
            confirmButtonText: "前往闯关",
            cancelButtonText: "返回学习中心",
            closeOnClickModal: false,
            closeOnPressEscape: false,
          })
            .then(() => {
              this.postStudyStep();
              this.$goRouter("spellTestAfterStudy", this.$route.query);
            })
            .catch(() => {
              this.$goRouter("naturalSpellCenter", this.$route.query);
            });
        }
      });
    },
    setTimer() {
      this.timer = setInterval(() => {
        this.testTime++;
      }, 1000);
    },
    selectContent() {
      this.content = this.listenWordList.filter(item => item.id == this.spellId)[0].content
    }
  },
  created() {
    this.listenWordList = JSON.parse(localStorage.getItem("spellCheckeWordlist"))
    this.title = this.$route.query.checkedTitle;
    this.spellId = Number(this.$route.query.checkedTypeId);
    this.selectContent()
    this.getNaturalSpellWord();
  },
  components: {
    ListenTestItem,
  },
};
</script>